#include "Renderer.h"
#include "Point2d_gl.h"

#include <gl.h>
#include <SDL.h>

namespace Lame3d
{
	Renderer::Renderer(TextureManager &tm, const InputManager &iM, const DisplayManager &dM, const Cursor &c, FontManager &fM)
			: textureManager(tm), inputManager(iM), displayManager(dM), cursor(c), fontManager(fM), clearColor(0, 0, 0), fpsColor(1, .5, 1)
	{
		
	}
	
	Renderer::~Renderer()
	{
	}
	
	Color& Renderer::ClearColor()
	{
		return clearColor;
	}
	
	void Renderer::Render()
	{
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		// 2d stuff
		enter2dMode();
		drawFPS();
		drawMouse();
		leave2dMode();
		
		SDL_GL_SwapBuffers();
	}
	
	void Renderer::enter2dMode()
	{
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		glOrtho(0, 
				displayManager.CurrentConfig().Width/float(displayManager.CurrentConfig().Height)
				, 0, 1, -1, 1);
		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glLoadIdentity();
	}
	
	void Renderer::leave2dMode()
	{
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
	}
	
	void Renderer::drawFPS()
	{
		Font::Handle fHand = fontManager.Request("mono.ttf", fpsColor, 12).GetHandle();
		char buf[16];
		sprintf(buf, "%f FPS", 1.0/fpsTimer.Seconds());
		glPushMatrix();
		glTranslatef(0, 1, 0);
		fHand.Print(buf, displayManager.Ratio(), false);
		glPopMatrix();
	}
	
	void Renderer::drawMouse()
	{
		Point2d p2(cursor.Size());
		p2 /= 2.0;
		glTranslate(inputManager.MouseLocation());
		Texture::Handle handle = textureManager[cursor.TextureName()].GetHandle();
		handle.Bind2d();
		glTranslatef(0, 0, .2);
		glBegin(GL_QUADS);
		handle.Coord(0, 0);
		glVertex2f(-p2[0], -p2[1]);
		handle.Coord(1, 0);
		glVertex2f(p2[0], -p2[1]);
		handle.Coord(1, 1);
		glVertex2f(p2[0], p2[1]);
		handle.Coord(0, 1);
		glVertex2f(-p2[0], p2[1]);
		glEnd();
	}
}

// eof //
